﻿using E_GovernmentSystem.Models;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace E_GovernmentSystem.Controllers
{
    /// <summary>
    /// 角色管理
    /// </summary>
    public class RoleManageController : Controller
    {

        //配置数据库上下文
        private readonly SqlSugar.ISqlSugarClient db;

        public RoleManageController(SqlSugar.ISqlSugarClient _db)
        {
            this.db = _db;
        }

        //角色管理主页
        public IActionResult Index()
        {
            return View();
        }

        //获取角色信息
        public IActionResult getRoleInfo(int page, int limit, string strName)
        {

            int total = 0;
            List<role> list = db.Queryable<role>()
                    .Where(a => (string.IsNullOrEmpty(strName) || a.RoleName.Contains(strName)))
                     .OrderByDescending(a => a.RoleId)
                     .ToPageList(page, limit, ref total);

            var json = new
            {
                code = 0,
                data = list,
                count = total,
                msg = ""
            };
            return Json(json);
        }

        //保存角色信息
        [HttpPost]
        public IActionResult Save(role role)
        {
            bool res = (db.Storageable(role).DefaultAddElseUpdate().ExecuteCommand()) > 0 ? true : false;

            return Json(res);
        }

        //删除
        [HttpPost]
        public IActionResult Delete(string ids)
        {
            bool res = false;
            if (!string.IsNullOrEmpty(ids))
            {
                if (ids.Contains(','))
                {
                    string[] idArr = ids.Split(',');
                    int[] intArr = Array.ConvertAll(idArr, int.Parse);
                    res = db.Deleteable<usertable>().In(intArr).ExecuteCommand() > 0;
                }
                else
                {
                    int id = int.Parse(ids);
                    res = db.Deleteable<usertable>().In(id).ExecuteCommand() > 0;
                }
            }
            return Json(res);
        }
    }
}
